package com.nuc.seckill.utils;

import com.google.common.collect.Lists;
import com.nuc.seckill.base.Constant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * 削减库存
 *
 * @author 石一歌
 * @date 2022-08-11 15:38
 */
@Component
@Slf4j
public class DecrCacheStockUtil {
    private final String subStock = "local key=KEYS[1];\n" +
            "local surplusStock = tonumber(redis.call('get',key));\n" +
            "if (surplusStock<=0) then return 0\n" +
            "else\n" +
            "    redis.call('incrby', key, -1)\n" +
            "    return 2 \n" +
            "end";
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    private DefaultRedisScript<Long> getRedisScript;

    /**
     * 初始化Constructor >> @Autowired >> @PostConstruct
     * 在项目启动的时候执行这个方法，可作为一些数据的常规化加载
     *
     * @author 石一歌
     * @date 2022/8/11 15:39
     */
    @PostConstruct
    public void init() {
        getRedisScript = new DefaultRedisScript<>();
        getRedisScript.setResultType(Long.class);
        getRedisScript.setScriptText(subStock);
    }

    /**
     * 减库存
     *
     * @param productId 产品id
     * @return java.lang.Long
     * @author 石一歌
     * @date 2022/8/11 15:41
     */
    public Long decrStock(Long productId) {
        return redisTemplate.execute(getRedisScript, Lists.newArrayList(String.format(Constant.RedisKey.SECKILL_SALED_COUNT, productId)));
    }

    /**
     * 加库存
     *
     * @param productId 产品id
     * @author 石一歌
     * @date 2022/8/11 15:40
     */
    public void addStock(Long productId) {
        String key = String.format(Constant.RedisKey.SECKILL_SALED_COUNT, productId);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))) {
            redisTemplate.opsForValue().increment(key);
        }
    }
}
